<template>
	<view>
		<view class="text-area" v-for="it in users">
					<text class="title">{{it.name}}</text>
					<!-- <image :src="it.img" mode=""></image> -->
					<button @click="set(it.id)">私信</button>
		</view>
		<view class="cont">
			<view class="title" v-for="(item,index) in msgList" :key="index"
				:style="item.fromUser == this.loginUserId ?'text-align: right;':'text-align: left;'">
				用户{{item.fromUser}}说：{{item.msg}}
			</view>
		</view>
		
		<view class="c">
			<input v-model="content" placeholder="请输入内容" />
		</view>
		<view>
			<button @click="send">发送</button>
		</view>
		
	</view>
</template>
 
<script>
	export default {
		data() {
			return {
				title: 'Hello',
				socketOpen: false,
				socketMsgQueue: [],
				username:'cc',
				loginUserId: 2, //当前登录的用户id
				content: '', //发送的内容
				msgList: [],
				users:[],
				frienduser:[],
				toName:"q"
			}
		},
		onLoad(option) {
			
			let that = this;
			const c=uni.getStorageSync("username");
			console.log('赋值');
			console.log(c.username);
			that.username=c.username;
			that.loginUserId=1;
			console.log(that.username);
			console.log(that.loginUserId);
			//页面加载后，建立websocket连接
			uni.connectSocket({
				url: 'ws://localhost:9090/imserver/' + this.loginUserId
			});
 
			uni.onSocketOpen(function(res) {
				that.socketOpen = true;
				for (var i = 0; i < that.socketMsgQueue.length; i++) {
					that.sendSocketMessage(that.socketMsgQueue[i]);
				}
				that.socketMsgQueue = [];
			});
 
			uni.onSocketMessage(function(res) {
				console.log('收到服务器内容：' + res.data);
				if (res.data != 'conn_success') {
					that.msgList.push(JSON.parse(res.data))
				}
			});
			uni.request({
				url: 'http://localhost:9001/user/getFollowUser/'+this.loginUserId,
				method: 'GET',
				data: this.users,
				success: res => {
					if(res.statusCode == 404){
						uni.showToast({
							title: '密码或用户名错误',
						});
						return;
					}
					that.users=res.data.data;
					console.log(res.data);
				},
				fail: () => {	
				},
				complete: () => {}
			});	
 
		},
		methods: {
			send() {
				this.sendSocketMessage(this.content)
				this.content = ''
			},
			sendSocketMessage(msg) {
				if (this.socketOpen) {
					uni.sendSocketMessage({
						data: msg
					});
				} else {
					this.socketMsgQueue.push(msg);
				}
			},
			get(){	
					
				},
				set(id){
					console.log("该用户为"+id)
				}
		}
	}
</script>
 
<style>
	.title {
		text-align: left;
		font-size: 36rpx;
		color: #8f8f94;
	}
	.c{
		width: 100px;
		height: 200px;
	}
	.cont{
		width: auto;
		height: 200px;
		background-color: beige;
	}
	
</style>